const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

const { testConnection } = require('./config/database');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 测试数据库连接
testConnection();

// 路由
const brandRoutes = require('./routes/brand');
const categoryRoutes = require('./routes/category');
const couponRoutes = require('./routes/coupon');
const orderRoutes = require('./routes/order');
const userRoutes = require('./routes/user');
const addressRoutes = require('./routes/address');

// 使用路由
app.use('/api/brand', brandRoutes);
app.use('/api/category', categoryRoutes);
app.use('/api/coupon', couponRoutes);
app.use('/api/order', orderRoutes);
app.use('/api/user', userRoutes);
app.use('/api/address', addressRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({ 
    message: '商城系统API服务',
    version: '1.0.0',
    status: 'running'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.originalUrl
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});